package com.jic.veteran.common.leaf;

import com.alibaba.druid.pool.DruidDataSource;
import com.jic.veteran.common.leaf.common.PropertyFactory;
import com.jic.veteran.common.leaf.common.Result;
import com.jic.veteran.common.leaf.segment.SegmentIDGenImpl;
import com.jic.veteran.common.leaf.segment.dao.IDAllocDao;
import com.jic.veteran.common.leaf.segment.dao.impl.IDAllocDaoImpl;
import com.jic.veteran.common.leaf.snowflake.SnowflakeIDGenImpl;

import java.sql.SQLException;
import java.util.Properties;

public class LeafSegmentIdBuilder {
    private static final Properties properties;
    private static final DruidDataSource dataSource;
    private static final IDGen idGen;

    static {
        properties = PropertyFactory.getProperties();
        // Config dataSource
        dataSource = new DruidDataSource();
        dataSource.setUrl(properties.getProperty("jdbc.url"));
        dataSource.setUsername(properties.getProperty("jdbc.username"));
        dataSource.setPassword(properties.getProperty("jdbc.password"));
        try {
            dataSource.init();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        // Config Dao
        IDAllocDao dao = new IDAllocDaoImpl(dataSource);

        // Config ID Gen
        idGen = new SegmentIDGenImpl();
        ((SegmentIDGenImpl) idGen).setDao(dao);
        idGen.init();
    }

    private static class InstanceHolder {
        private final static LeafSegmentIdBuilder instance = new LeafSegmentIdBuilder();
    }

    public static LeafSegmentIdBuilder getInstance() {
        return InstanceHolder.instance;
    }

    public String generateId(String key) {
        Result result = idGen.get(key);
        if(null != result) {
            return String.valueOf(result.getId());
        }
        return null;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10000; i++) {
            System.out.println(LeafSegmentIdBuilder.getInstance().generateId("generateProjectId"));
        }
    }
}
